package com.xfeng.httpconnect;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by lixianfeng on 15/12/9.
 *
 */
public class HttpRequest {

    private static final int DEFAULT_TIMEOUT = 10000;//连接超时

    private static final String HTTP_GET = "GET";
    private static final String HTTP_POST = "POST";

    //可以设置header和parames

    public void get(String paramurl){

        try {
            URL url = new URL(paramurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            //get请求
            connection.setRequestMethod(HTTP_GET);
            connection.setConnectTimeout(DEFAULT_TIMEOUT);

            //设置获取输入流
            connection.setDoInput(true);
            //设置输出流来读取数据
            ByteArrayOutputStream bas = new ByteArrayOutputStream();
            InputStream is = connection.getInputStream();
            int ch = 0;
            while(ch > -1){
                ch = is.read();
                bas.write(ch);
            }
            String result = new String(bas.toByteArray(), "utf-8");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}
